<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\AppModel;
use App\Utils\ResponseEnum;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AuthController extends ApiController
{
    const VERSION_CACHE_KEY = 'appVersion';

    /**
     * 接口授权获取token
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getToken(Request $request): JsonResponse
    {
        $app_key = $this->verifyString('app_key');
        $app_secret = $this->verifyString('app_secret');
        $app = AppModel::where('app_key', $app_key)->where('app_secret', $app_secret)->first();
        if (!$app)
            return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED);
        $token = $app->createToken('my-app-token')->plainTextToken;
        return $this->success(['token' => $token]);
    }

    /**
     * 获取APP最新版本信息
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getAppVersion(): JsonResponse
    {
        $type = $this->verifyInteger('type');
        if (!Cache::has(self::getCacheKeyName($type)))
            self::setAppVersionCache($type);
        return $this->success(Cache::get(self::getCacheKeyName($type)));
    }

    /**
     * 新建或更新APP版本信息
     * @param Request $request
     * @return JsonResponse
     */
    public function saveAppVersion(Request $request): JsonResponse
    {
        $data = $request->except(['app_id']);
        if ($request->input('id'))
            AppModel::where('id', $request->input('id'))->update($data);
        else
            AppModel::create($data);
        self::setAppVersionCache($data['type']);
        return $this->success();
    }

    /**
     * 授权过期
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        return $this->fail(ResponseEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED);
    }

    /**
     * 获取缓存字段
     * @param int $type
     * @return string
     */
    public static function getCacheKeyName(int $type): string
    {
        return self::VERSION_CACHE_KEY . $type;
    }

    /**
     * 创建缓存
     * @param int $type
     * @return void
     */
    private function setAppVersionCache(int $type): void
    {
        $app = AppModel::where('type', $type)->first();
        Cache::put(self::getCacheKeyName($type), $app);
    }
}
